import { createRouter, createWebHistory } from "vue-router";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/login",
      component: () => import("../views/login/index.vue"),
      name: "Login",
    },
    {
      path: "/",
      component: () => import("../views/chat/index.vue"),
      name: "Chat",
    },
  ],
});

router.beforeEach((to, from, next) => {
  const username = localStorage.getItem("username");

  if (username) {
    // 登录了
    if (to.path === "/login") {
      next("/");
    } else {
      next();
    }
  } else {
    // 没有登录
    if (to.path === "/login") {
      next();
    } else {
      next("/login");
    }
  }
});

export default router;
